var tchTrackList;
var classList;
var appList;
var iSWId;
var mTchTrack;
var mTaskTrack;
var mAppAnalyze;
var mPClass;
var List = [];
var url='';
var FileUrl='';
var clickFlag=false;
$(document).ready(function () {

    tchTrackList = $('#tchTrackList');
    classList    = $('#classList');
    taskList     = $('#taskList');
    appList      = $('#appList');
    iSchoolId    = addressUri.getParam('schoolId');
    iSWId        = null;



    //伸缩点击事件
    $('.widget-collapse-option').click(function()	{
        $activeWidget = $(this).parent().parent().parent();

        $activeWidget.find('.smart-widget-inner').slideToggle();
        $activeWidget.toggleClass('smart-widget-collapsed');

        var $activeSpinIcon = $activeWidget.find('.refresh-icon-animated').fadeIn();

        setTimeout(function() {
            $activeSpinIcon.fadeOut();
        },50);

        $activeWidget = '';

        return false;
    });
    appList.parent().parent().parent().find('.widget-collapse-option').click();
    taskList.parent().parent().parent().find('.widget-collapse-option').click();
    classList.parent().parent().parent().find('.widget-collapse-option').click();
    tchTrackList.parent().parent().parent().find('.widget-collapse-option').click();

    if(info=='1'){
        loadData();
    }else {
        iSWId = info['iSWId'];
        iSchoolId = info['iSchoolId'];
        if(info['iState']==0){  //数据重新获取
            loadData();
        }else {  //直接取保存的数据
            initClassList(JSON.parse(info['mPClass']));
            initTchTrackList($.parseJSON( info['mTchTrack'] ));
            initTaskList($.parseJSON( info['mTaskTrack'] ));
            initApp($.parseJSON( info['mAppAnalyze'] ));
        }

        $('#mSummary').val(info['mSummary']);
        $('#mPlan').val(info['mPlan']);
        if(info['iState']==0 || info['iState']== 3){
            $('#pass').parent().hide();
            $('#save').parent().show();

        }else if(info['iState']==1){
            $('#save').parent().hide();
            $('#pass').parent().show();
        }else {
            $('#pass').parent().hide();
            $('#save').parent().hide();
        }
        $('#startDay').val(info['startDay']);
        $('#endDay').val(info['endDay']);
        showFileList(info['sImages'],info['sFiles'],info['iSWId']);

    }

    $('#btn_view').click(function () {
        loadData();
    });


    function showFileList(sImages,sFiles,keyId) {
        // $('#fileList').empty();
        var contentStr = '<table style="width: 100%;"><tr><td>'+timeLine.showImage(sImages,keyId,'',true)+'</td></tr>' +
            '<tr><td>'+timeLine.showFile(sFiles,keyId,'',true)+'</td></tr>' +
            '</table>';
        if (!sImages && !sFiles) {
            contentStr = '无附件';
        }
        $('#fileList').empty().append(contentStr);

        $('.images').viewer();
    }


    //删除图片ajax
    $('#fileList').on('click','[id^=imageDelete_]',function () {
        var iSWId=$(this).attr("id").split("_")[1];
        var rmId=$(this).attr('id').split('_')[2];
        myWindow.initPopUp({text: '你确定要删除这张图片吗?'},function () {
            $.ajax({
                url:baseUrl+'school_week/ajaxDelete',
                data:{'id':iSWId,'rmId':rmId},
                dataType:'json',
                type:'post',
                success:function (data) {
                    //根据数据更新
                    location.reload();
                },
                error:function (result) {
                    console.log(result);
                }
            });
        });


    });


    //删除图片ajax
    $('#fileList').on('click','[id^=fileDelete_]',function () {
        var iSWId=$(this).attr("id").split("_")[1];
        var rmId=$(this).attr('id').split('_')[2];
        myWindow.initPopUp({text: '你确定要删除这个附件吗?'},function () {
            $.ajax({
                url:baseUrl+'school_week/ajaxDelete/fileDelete',
                data:{'id':iSWId,'rmId':rmId},
                dataType:'json',
                type:'post',
                success:function (data) {
                    //根据数据更新
                    location.reload();
                },
                error:function (result) {
                    console.log(result);
                }
            });
        });
    });

    $("#fileInput").fileinput('destroy');
    fileInput.initFileInput('fileInput',baseUrl+'school_week/ajaxUpload');
    
    var count=0; //记录上传次数
    $("#fileInput").on("fileuploaded", function (event, data, previewId, index) {
        count++;
        List.push({ FileName: data.response.fileName, KeyID: previewId,url:data.response.url })
        if(clickFlag&&(count==data.files.length)){
            clickFlag=false;
            count=0;
            save();
        }
    });

    $("#fileInput").on("filesuccessremove", function (event, data, previewId, index) {
        for (var i = 0; i < List.length; i++) {
            if (List[i].KeyID== data) {
                List.splice(i,1);
            }
        }
    });


    $('#save').click(function () { //保存
        $.ajax({
            url:baseUrl+'school_week/saveWeek',
            data:getParams(0),
            type:'POST',
            dataType:'json',
            success:function (data) {
                window.top.swal(
                    data['msg'],
                    '',
                    'success'
                );
                successDo();
            },
            error:function (data) {
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });

    $('#submit').click(function () { //提交
        $.ajax({
            url:baseUrl+'school_week/saveWeek',
            data:getParams(1),
            type:'POST',
            dataType:'json',
            success:function (data) {

                window.top.swal(
                    data['msg'],
                    '',
                    'success'
                );
                successDo();
            },
            error:function (data) {
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });

    $('#pass').click(function () {
        $.ajax({
            url:baseUrl+'school_week/saveWeek',
            data:getParams(2),
            type:'POST',
            dataType:'json',
            success:function (data) {
                window.top.swal(
                    data['msg'],
                    '',
                    'success'
                );
                successDo();
            },
            error:function (data) {
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });

    $('#back').click(function () {
        $.ajax({
            url:baseUrl+'school_week/saveWeek',
            data:getParams(3),
            type:'POST',
            dataType:'json',
            success:function (data) {
                window.top.swal(
                    data['msg'],
                    '',
                    'success'
                );
                successDo();
            },
            error:function (data) {
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });

});

function successDo() {
    if(iSWId != null){
        location.reload();
    }else {
        window.top.xhTop.closeActiveTab();
    }
}


function getDay() {
    var startDay = $('#startDay').val();
    var endDay   = $('#endDay').val();
    return {startDay:startDay , endDay:endDay};
}

function loadData() {
    $.ajax({
        url:baseUrl+'school_week/getTchTrack',
        data:{iSchoolId:iSchoolId,startDay:getDay().startDay,endDay:getDay().endDay},
        type:'POST',
        dataType:'json',
        success:function (data) {
            initTchTrackList(data);
        },
        error:function (data) {
            window.top.swal(
                data['responseText'],
                '',
                'error'
            );
        }
    });

    $.ajax({
        url:baseUrl+'school_week/getTaskTrack',
        data:{iSchoolId:iSchoolId,startDay:getDay().startDay,endDay:getDay().endDay},
        type:'POST',
        dataType:'json',
        success:function (data) {
            initTaskList(data);
        },
        error:function (data) {
            window.top.swal(
                data['responseText'],
                '',
                'error'
            );
        }
    });

    $.ajax({
        url:baseUrl+'school_week/getApp',
        data:{schoolId:iSchoolId,startDay:getDay().startDay,endDay:getDay().endDay},
        type:'POST',
        dataType:'json',
        success:function (data) {
            // console.log(data);
            initApp(data);
        },
        error:function (data) {
            // console.log(data);
            window.top.swal(
                data['responseText'],
                '',
                'error'
            );
        }
    });


    $.ajax({
        url:baseUrl+'school_week/getClass',
        data:{iSchoolId:iSchoolId,startDay:getDay().startDay,endDay:getDay().endDay},
        type:'POST',
        dataType:'json',
        success:function (data) {
            initClassList(data);
        },
        error:function (data) {
            window.top.swal(
                data['responseText'],
                '',
                'error'
            );
        }
    });
}


function getParams(iState) {
    var mSummary = $('#mSummary').val();
    var mPlan    = $('#mPlan').val();
    console.log(List);
    for (var i = 0; i < List.length; i++) {
        var footerfix= List[i]['url'].split('.');
        footerfix = footerfix[footerfix.length-1];
        footerfix = footerfix.toLowerCase()
        if(footerfix=='jpg'||footerfix=='gif'||footerfix=='png') {  //这里的url只指图片
            url += List[i]['url'] + ',';
        }else {
            FileUrl+=List[i]['url']+',';
        }
    }
    var params={iSWId:iSWId,mSummary:mSummary,mPlan:mPlan,iState:iState,mPClass:mPClass,mTchTrack:mTchTrack,mTaskTrack:mTaskTrack,mAppAnalyze:mAppAnalyze,iSchoolId:iSchoolId,iStartDay:getDay().startDay,iEndDay:getDay().endDay};
    if(url!=''){
        params.sImages =url;
    }
    if(FileUrl != ''){
        params.sFiles = FileUrl;
    }

    return params;
}

function initClassList(data) {
    mPClass = JSON.stringify(data);
    if( data!=null && data.length>0  ) {
        var str ='';
        str +='<tr class="info"> <th style="width: 120px;">教师名称</th> <th style="width: 120px">公开课时间</th> <th style="width: 150px">公开课类型</th><th style="width: 80px">类型</th> <th >内容</th> </tr>';

        $.each(data, function (index, rows) {
            var length = rows.length * 5;
            str += '<tr>' +
                '<td rowspan="' + length + '"  style="vertical-align: middle">' + rows[0]['sUserName'] + '</td>';

            $.each(rows, function (key, value) {
                str += '<td rowspan="5" style=" vertical-align: middle;">' + value['tStartTime'] + '</td>';
                str += '<td rowspan="5" style=" vertical-align: middle;">' + value['iPCType'] + '</td>';
                str += '<td>人员情况:</td><td>' + value['mAttendences'] + '</td></tr>';
                str += '<tr><td>备注:</td><td >' + value['mDesc'] + '</td></tr>';
                str += '<tr><td>主要内容:</td><td >' + value['mContent'] + '</td></tr>';
                str += '<tr><td>评价:<td >' + value['mEvaluate'] + '</td></tr>';
                str += '<tr><td>评价人:<td >' + value['iEvalId'];
                if (value['sSelfPhone'] != null) {
                    str += '(' + value['sSelfPhone'] + ')</td></tr>';
                } else {
                    str += '</td></tr>';
                }

            });
        })

        classList.empty().append(str);
    };
}

function initTchTrackList(data) {
    mTchTrack = JSON.stringify(data);
    if( data!=null && data.length>0) {
        var str ='';
        str +='<tr class="info"> <th style="width: 120px;">教师名称</th> <th style="width: 120px">跟踪时间</th> <th style="width: 80px">类型</th> <th >内容</th> </tr>';
        $.each(data, function (index, rows) {
            var length = rows.length * 4;
            str += '<tr>' +
                '<td rowspan="' + length + '" style=" vertical-align: middle;">' + rows[0]['sUserName'] + '</td>';

            $.each(rows, function (key, value) {
                str += '<td rowspan="4" style=" vertical-align: middle;">' + value['tTrackTime'] + '</td>';
                str += '<td>沟通目的:</td><td>' + value['mPurpose'] + '</td></tr>';
                str += '<tr><td>沟通内容:</td><td >' + value['mContent'] + '</td></tr>';
                str += '<tr><td>沟通结果:</td><td >' + value['mResult'] + '</td></tr>';
                str += '<tr><td>原因分析:</td><td >' + value['mAppUse'] + '</td></tr>';
            });
        })
        tchTrackList.empty().append(str);
    };
}

function initTaskList(data) {
    mTaskTrack = JSON.stringify(data);
    if(data!=null && data.length>0 ){
        var str ='';
        str +='<tr class="info" style="height: 35px"> <th style="width: 120px;">任务类型</th> <th style="width: 120px">任务名称</th> <th style="width: 120px">状态</th> <th >提问人</th> <th >创建时间</th> </tr>';
        $.each(data,function (index,row) {
            str +='<tr>';
            str += '<td>'+row['taskType']+'</td>';
            str += '<td>'+row['sTaskName']+'</td>';
            str += '<td>'+row['state']+'</td>';
            str += '<td>'+row['sOfferUserName']+'</td>';
            str += '<td>'+row['tCreateDate']+'</td>';
            str +='</tr>';
        })
        taskList.empty().append(str);
    };
}

function initCommon(data) {
    if(data!=null && data.length>0 ) {
        var str = '';
        str+='<tr class="info"> <th colspan="3">考核项目</th> <th colspan="9">云作业</th> <th>有效课堂</th> </tr>';
        str+='<tr class="info"> <th rowspan="3">老师/班级</th> <th rowspan="3">班级数量</th> <th rowspan="3">学生数量</th> <th rowspan="2" colspan="4">基础项</th> <th colspan="5">附加项</th> <th rowspan="3">完成次数</th> </tr>';
        str+='<tr class="info"> <th colspan="2">分层</th> <th >错题卷组</th> <th >微课</th> <th >二次批改</th> </tr>';
        str+='<tr class="info"> <th>完成次数</th> <th>平均题量</th> <th>上交率</th> <th>批改率</th> <th>完成次数</th> <th>完成比例</th> <th>完成次数</th> <th>录制次数</th> <th>批改次数</th> </tr>';
        $.each(data, function (index, row) {
            str += '<tr>';
            str += '<td>' + row['tchName'] + '<br>' + row['classNames'].join(',') + '</td>';
            str += '<td>' + row['classNum'] + '</td>';
            str += '<td>' + row['stuNum'] + '</td>';
            str += '<td>' + row['cloudTask']['taskFixNum'] + '</td>';
            str += '<td>' + row['cloudTask']['avgTopicNum'] + '</td>';
            str += '<td>' + (row['cloudTask']['uploadRate'] * 100).toFixed(2) + '%</td>';
            str += '<td>' + (row['cloudTask']['correctRate'] * 100).toFixed(2) + '%</td>';
            str += '<td>' + row['cloudTask']['taskGroupNum'] + '</td>';
            str += '<td>' + (row['cloudTask']['completeGroupRate'] * 100).toFixed(2) + '%</td>';
            str += '<td>' + row['cloudTask']['taskWrongNum'] + '</td>';
            str += '<td>' + row['cloudTask']['coursewareNum'] + '</td>';
            str += '<td>' + row['cloudTask']['taskRecorrectNum'] + '</td>';
            str += '<td>' + row['ztClass']['taskValidNum'] + '</td>';
            str += '</tr>'
        })
        $('#common').find('table').empty().append(str);
    };
}

function initBrash(data,seletor) {
    if(data!=null && data.length>0 ) {
        var str = '';
        str+='<tr class="info"> <th >班级</th> <th >老师</th> <th>人均题量</th> <th>布置次数</th> <th>上交率</th> </tr>';
        $.each(data, function (index, row) {
            str += '<tr>';
            str += '<td>' + row['className'] + '</td>';
            str += '<td>' + row['tchName'] + '</td>';
            str += '<td>' + row['practiceNum'] + '</td>';
            str += '<td>' + row['taskFixNum'] + '</td>';
            str += '<td>' + (row['uploadRate'] * 100).toFixed(2) + '%</td>';
            str += '</tr>'
        })
        $('#'+seletor).find('table').empty().append(str);
    };
}

function initTrans(data,seletor) {
    if(data!=null && data.length>0 ) {
        var str = '';
        str+='<tr class="info"> <th>班级</th> <th>老师</th> <th>完成次数</th> </tr>';
        $.each(data, function (index, row) {
            str += '<tr>';
            str += '<td>' + row['className'] + '</td>';
            str += '<td>' + row['tchName'] + '</td>';
            str += '<td>' + row['taskFixNum'] + '</td>';
            str += '</tr>'
        })
        $('#'+seletor).find('table').empty().append(str);
    };
}
function initApp(data) {
    mAppAnalyze = JSON.stringify(data);
    // console.log(data);
    if(data == []){
        return false;
    }
    initCommon(data['common']);
    initBrash(data['brush']['chinese'],'brush_chinese');
    initBrash(data['brush']['chineseColl'],'brush_chineseColl');
    initBrash(data['brush']['english'],'brush_english');
    initBrash(data['brush']['math'],'brush_math');
    initBrash(data['brush']['science'],'brush_science');
    initTrans(data['chineseBasic'],'chinese_basic');
    initTrans(data['speakTrain'],'speak_train');
}